package com.yksj.healthtalk.wallet;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.unionpay.UPPayAssistEx;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.PayActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.ui.R;

/**
 * 充值
 * 
 * @author Administrator
 * 
 */
public class TopUpActivity extends BaseFragmentActivity implements
		OnClickListener {

	private String money;
	private static final int PLUGIN_NOT_INSTALLED = -1;
	private static final int PLUGIN_NEED_UPGRADE = 2;

	/*****************************************************************
	 * mMode参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
	 *****************************************************************/
	private String mMode = "00";

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.top_up);
		initWidget();
		initDate();
	}

	private void initDate() {
		money = getIntent().getStringExtra("money");
	}

	private void initWidget() {
		initTitle();
		titleTextV.setText("选择支付方式");
		titleLeftBtn.setOnClickListener(this);
	}

	// 支付宝
	public void onClickAlipay(View v) {
		HttpRestClient.doHttpTopUp(money, "10", new AyncHander());
	}

	// 银联
	public void onClickUnionpay(View v) {
		HttpRestClient.doHttpTopUp(money, "20", new AyncHander());
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;

		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		setResult(RESULT_OK);
		finish();
	}

	// class AyncHander extends JsonsfHttpResponseHandler{
	//
	// @Override
	// public void onSuccess(int statusCode, JSONObject response) {
	// if (response.containsKey("error_message")) {
	// SingleBtnFragmentDialog.show(getSupportFragmentManager(), "提示",
	// response.getString("error_message"), "确定");
	// }else if(response.containsKey("tn")){
	// // {"PAY_ID":"1140227007141885","tn":"201402271420460080192"}
	// /*************************************************
	// *
	// * 步骤2：通过银联工具类启动支付插件
	// *
	// ************************************************/
	// // mMode参数解释：
	// // 0 - 启动银联正式环境
	// // 1 - 连接银联测试环境
	// int ret = UPPayAssistEx.startPay(TopUpActivity.this, null, null,
	// response.getString("tn"), mMode);
	// if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
	// // 需要重新安装控件
	// AlertDialog.Builder builder = new
	// AlertDialog.Builder(TopUpActivity.this);
	// builder.setTitle("提示");
	// builder.setMessage("完成购买需要安装银联支付控件，是否安装？");
	//
	// builder.setNegativeButton("确定",
	// new DialogInterface.OnClickListener() {
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	// dialog.dismiss();
	// UPPayAssistEx.installUPPayPlugin(TopUpActivity.this);
	// }
	// });
	//
	// builder.setPositiveButton("取消",
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	// dialog.dismiss();
	// }
	// });
	// builder.create().show();
	//
	// }
	// super.onSuccess(statusCode, response);
	// }
	// }
	//
	// @Override
	// public void onFailure(Throwable error, String content) {
	// super.onFailure(error, content);
	// }
	//
	// @Override
	// public void onStart() {
	// // TODO Auto-generated method stub
	// super.onStart();
	// }
	//
	// @Override
	// public void onSuccess(int statusCode, String content) {
	// if(content.contains("支付宝")) {
	// Intent intent = new Intent(getApplicationContext(),PayActivity.class);
	// intent.putExtra("summary", content);
	// startActivity(intent);
	// finish();
	// }
	// super.onSuccess(statusCode, content);
	// }
	//
	// @Override
	// public void onFinish() {
	// // TODO Auto-generated method stub
	// super.onFinish();
	// }
	// }

	class AyncHander extends AsyncHttpResponseHandler {
		public AyncHander() {
			super(TopUpActivity.this);
		}
		@Override
		public void onSuccess(int statusCode, String content) {
			try {
				JSONObject response = JSON.parseObject(content);
				if (response.containsKey("error_message")) {
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),
							 response.getString("error_message"));
				} else if (response.containsKey("tn")) {
					// {"PAY_ID":"1140227007141885","tn":"201402271420460080192"}
					/*************************************************
					 * 
					 * 步骤2：通过银联工具类启动支付插件
					 * 
					 ************************************************/
					// mMode参数解释：
					// 0 - 启动银联正式环境
					// 1 - 连接银联测试环境
					int ret = UPPayAssistEx.startPay(TopUpActivity.this, null,
							null, response.getString("tn"), mMode);
					if (ret == PLUGIN_NEED_UPGRADE
							|| ret == PLUGIN_NOT_INSTALLED) {
						// 需要重新安装控件
						AlertDialog.Builder builder = new AlertDialog.Builder(
								TopUpActivity.this);
						builder.setTitle("提示");
						builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

						builder.setNegativeButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
										UPPayAssistEx
												.installUPPayPlugin(TopUpActivity.this);
									}
								});

						builder.setPositiveButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});
						builder.create().show();
					}
				}
			} catch (Exception e) {
				if (content.contains("支付宝")) {
					Intent intent = new Intent(getApplicationContext(),
							PayActivity.class);
					intent.putExtra("summary", content);
					startActivity(intent);
				}
			}
			super.onSuccess(statusCode, content);
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent data) {
		/*************************************************
		 * 
		 * 步骤3：处理银联手机支付控件返回的支付结果
		 * 
		 ************************************************/
		if (data == null) {
			return;
		}

		String msg = "";
		/*
		 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
		 */
		String str = data.getExtras().getString("pay_result");
		if (str.equalsIgnoreCase("success")) {
			msg = "支付成功！";
		} else if (str.equalsIgnoreCase("fail")) {
			msg = "支付失败！";
		} else if (str.equalsIgnoreCase("cancel")) {
			msg = "用户取消了支付";
		}

		SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), msg
				);
		super.onActivityResult(arg0, arg1, data);
	}

}
